﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.Utils
{
  public class HttpPostResult
  {
    public HttpStatusCode Code { get; internal set; }
    public string Data { get; internal set; }
  }

  /// <summary>
  /// 
  /// </summary>
  public static partial class Extensions
  {
    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="contentType"></param>
    /// <param name="timeout"></param>
    /// <param name="headers"></param>
    /// <returns></returns>
    public async static Task<string> HttpGet(
        this string url)
    {
      var client = new WebClient();
      var content = string.Empty;
      content = await client.DownloadStringTaskAsync(url);
      return content;
    }

    /// <summary>
    /// 提交指定的字符串，无返回结果，通过onSuccess、onError回调来获取返回结果
    /// </summary>
    /// <param name="request"></param>
    /// <param name="body"></param>
    /// <param name="onSuccess"></param>
    /// <param name="onError"></param>
    /// <param name="headers"></param>
    /// <param name="timeout"></param>
    /// <param name="contentType"></param>
    public static HttpPostResult Submit(
        this HttpWebRequest request
        , string body = null
        , string contentType = "application/json"
        , int timeout = 5000
        , string[] headers = null)
    {
      //添加Headers
      if (headers.IsNotNullOrEmpty())
      {
        foreach (var header in headers)
        {
          request.Headers.Add(header);
        }
      }
      request.Timeout = timeout;
      var submitData = body.ToByteArray();
      request.Method = "POST";
      request.ContentType = contentType;
      request.ContentLength = submitData.Length;
      #region 主体代码部分
      using (var requestStream = request.GetRequestStream())
      {
        if (submitData != null)
        {
          requestStream.Write(submitData, 0, submitData.Length);
        }
        using (var response = request.GetResponse())
        {
          var httpResponse = response as HttpWebResponse;
          using (var stream = response.GetResponseStream())
          {
            var content = stream.ReadAllText();
            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
              //如果返回的状态码不是200，则将状态码作为errorCode返回
              content = $"POST操作失败！错误信息：{content}";
            }
            return new HttpPostResult { Code = httpResponse.StatusCode, Data = content };
          }
        }
      }
      #endregion
    }

    /// <summary>
    /// 异步方式提交指定的字符串，无返回结果，通过onSuccess、onError回调来获取返回结果
    /// </summary>
    /// <param name="request"></param>
    /// <param name="body"></param>
    /// <param name="onSuccess"></param>
    /// <param name="onError"></param>
    /// <param name="headers"></param>
    /// <param name="timeout"></param>
    /// <param name="contentType"></param>
    public static async Task<HttpPostResult> SubmitAsync(
        this HttpWebRequest request
        , string body = null
        , string contentType = "application/json"
        , int timeout = 5000
        , string[] headers = null)
    {
      //添加Headers
      if (headers.IsNotNullOrEmpty())
      {
        foreach (var header in headers)
        {
          request.Headers.Add(header);
        }
      }
      var submitData = body.ToByteArray();
      request.Method = "POST";
      request.Timeout = timeout;
      request.ContentType = contentType;
      request.ContentLength = submitData.Length;
      using (var requestStream = await request.GetRequestStreamAsync())
      {
        if (submitData != null)
        {
          requestStream.Write(submitData, 0, submitData.Length);
        }
        using (var response = await request.GetResponseAsync())
        {
          var httpResponse = response as HttpWebResponse;
          using (var stream = response.GetResponseStream())
          {
            var content = await stream.ReadAllTextAsync();
            return new HttpPostResult { Code = httpResponse.StatusCode, Data = content };
          }
        }
      }
    }

    /// <summary>
    /// 提交数据，无返回结果，通过onSuccess、onError回调来获取返回结果
    /// </summary>
    /// <param name="url"></param>
    /// <param name="body"></param>
    /// <param name="onSuccess"></param>
    /// <param name="onError"></param>
    /// <param name="contentType"></param>
    /// <param name="timeout"></param>
    /// <param name="headers"></param>
    public static HttpPostResult Submit(
        this string url
        , string body = null
        , string contentType = "application/json"
        , int timeout = 5000
        , string[] headers = null)
    {
      var request = WebRequest.CreateHttp(url);
      return request.Submit(body, contentType, timeout, headers);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="url"></param>
    /// <param name="body"></param>
    /// <param name="onSuccess"></param>
    /// <param name="onError"></param>
    /// <param name="contentType"></param>
    /// <param name="timeout"></param>
    /// <param name="headers"></param>
    public static async Task<HttpPostResult> SubmitAsync(
        this string url
        , string body = null
        , string contentType = "application/json"
        , int timeout = 5000
        , string[] headers = null)
    {
      var request = WebRequest.CreateHttp(url);
      return await request.SubmitAsync(body, contentType, timeout, headers);
    }
  }
}
